<?php

namespace app\admin\service;

use app\admin\model\Region as RegionMdl;

use think\Db;
use think\Exception;

class Region
{

    /**
     * 得到树形地址
     */
    public static function getDistrict(){
        $model = new RegionMdl();
        $districts = $model->where(['level' => 1])->select();
        foreach ($districts as &$item) {
            $city = $model->where(['parent_id' => $item['id']])->select();
            $item['child'] = $city;
        }

        return $districts;
    }

    /**
     * 获取地区
     */
    public static function getRegion($request){
        $model = new RegionMdl();
        $params = $request->param();
        $parentId = $params['p_id'];
        $selected = isset($params['selected']) ? $params['selected'] : 0;
        $level = $params['level'];
        $data = $model->where("parent_id = {$parentId} and level = {$level}")->select();
        $html = '';
        if($data){
            foreach($data as $h){
                if($h['id'] == $selected){
                    $html .= "<option value='{$h['id']}' selected>{$h['name']}</option>";
                }
                $html .= "<option value='{$h['id']}'>{$h['name']}</option>";
            }
        }

        return json($html);
    }

}